package com.javaee.demov2.service.impl;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javaee.demov2.persistent.entity.Book;
import com.javaee.demov2.persistent.mapper.BookMapper;
import com.javaee.demov2.service.BookService;
import com.javaee.demov2.utils.bean.PageResult;
import com.javaee.demov2.utils.bean.SysConstants;
import com.javaee.demov2.utils.response.ServiceException;

import com.javaee.demov2.web.dto.book.BookAddDto;
import com.javaee.demov2.web.dto.book.BookQueryDto;
import com.javaee.demov2.web.dto.book.BookUpdateDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * BookService类实现类
 */

@Transactional
@Service
@Slf4j
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {


    /**
     * 添加图书
     */
    @Override
    public void add(BookAddDto bookAddDto) {
        Book book = new Book();
        // 逻辑判断
        // 图书书号不能重复
        if (isExistBookISBN(bookAddDto.getIsbn())) {
            throw new ServiceException("图书书号已经存在");
        }

        // 将dto数据复制到book实体类
        BeanUtils.copyProperties(bookAddDto, book);
        // 设置默认状态和密码
        book.setStatus(SysConstants.ACTIVED);
        super.save(book);
    }


    /**
     * 复杂条件查询
     */
    @Override
    public PageResult<Book> query(BookQueryDto queryDto) {
        // 创建分页对象
        Page page = queryDto.getPage();

        // 分页查询
        Page<Book> result = super.lambdaQuery()
                .like(StringUtils.isNotBlank(queryDto.getTitile()), Book::getTitle, queryDto.getTitile())
                .like(StringUtils.isNotBlank(queryDto.getAuthor()), Book::getAuthor, queryDto.getAuthor())
                .eq(queryDto.getLanguage() != null, Book::getLanguage, queryDto.getLanguage())

                .like(StringUtils.isNotBlank(queryDto.getPublisher()), Book::getPublisher,
                        queryDto.getPublisher())
                .like(StringUtils.isNotBlank(queryDto.getPublisher()), Book::getPublisher,
                        queryDto.getPublisher())
                .page(page);

        //将分页查询结果转换为PageResult的形式
        return PageResult.fromPage(result);
    }

    @Override
    public Book findByBookTitle(String title) {
        return super.lambdaQuery().like(Book::getTitle, title).one();
    }


    /**
     * 更新图书信息
     */
    @Override
    public void update(BookUpdateDto updateDto) {
        Book book = new Book();
        // 将dto转换为book实体类
        BeanUtils.copyProperties(updateDto, book);
        super.updateById(book);
    }

    @Override
    public boolean isExistBookISBN(String isbn) {
        return super.lambdaQuery().eq(Book::getIsbn, isbn).count() > 0;
    }

}
